<%- include('layout', { title: '仪表板', active: 'dashboard' }) %>

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
    <!-- 统计卡片 -->
    <div class="anime-card p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">我的服务器</p>
                <p class="text-2xl font-bold text-gray-900" id="myServersCount">0</p>
            </div>
            <div class="bg-blue-100 p-3 rounded-full">
                <i class="fas fa-server text-blue-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="anime-card p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">运行中</p>
                <p class="text-2xl font-bold text-green-600" id="runningServersCount">0</p>
            </div>
            <div class="bg-green-100 p-3 rounded-full">
                <i class="fas fa-play-circle text-green-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="anime-card p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">在线节点</p>
                <p class="text-2xl font-bold text-purple-600" id="onlineNodesCount">0</p>
            </div>
            <div class="bg-purple-100 p-3 rounded-full">
                <i class="fas fa-network-wired text-purple-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="anime-card p-6">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm font-medium text-gray-600">系统状态</p>
                <p class="text-2xl font-bold text-green-600">正常</p>
            </div>
            <div class="bg-green-100 p-3 rounded-full">
                <i class="fas fa-heartbeat text-green-600 text-xl"></i>
            </div>
        </div>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- 我的服务器列表 -->
    <div class="lg:col-span-2">
        <div class="anime-card p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-server mr-2 text-blue-500"></i>我的服务器
                </h2>
                <button onclick="showCreateServerModal()" 
                        class="anime-button px-4 py-2 text-sm">
                    <i class="fas fa-plus mr-2"></i>创建服务器
                </button>
            </div>
            
            <div id="serversList" class="space-y-4">
                <!-- 服务器列表将在这里动态加载 -->
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-server text-4xl mb-4"></i>
                    <p>暂无服务器，点击上方按钮创建您的第一个服务器</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统信息 -->
    <div class="space-y-6">
        <!-- 快速操作 -->
        <div class="anime-card p-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-bolt mr-2 text-yellow-500"></i>快速操作
            </h3>
            <div class="space-y-3">
                <button onclick="showCreateServerModal()" 
                        class="w-full bg-gradient-to-r from-blue-500 to-blue-600 text-white py-2 px-4 rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all">
                    <i class="fas fa-plus mr-2"></i>创建服务器
                </button>
                <button onclick="window.location.href='/servers'" 
                        class="w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-2 px-4 rounded-lg hover:from-green-600 hover:to-green-700 transition-all">
                    <i class="fas fa-list mr-2"></i>管理服务器
                </button>
                <% if (user.role === 'admin') { %>
                    <button onclick="window.location.href='/nodes'" 
                            class="w-full bg-gradient-to-r from-purple-500 to-purple-600 text-white py-2 px-4 rounded-lg hover:from-purple-600 hover:to-purple-700 transition-all">
                        <i class="fas fa-network-wired mr-2"></i>管理节点
                    </button>
                    <button onclick="window.location.href='/settings'" 
                            class="w-full bg-gradient-to-r from-gray-500 to-gray-600 text-white py-2 px-4 rounded-lg hover:from-gray-600 hover:to-gray-700 transition-all">
                        <i class="fas fa-cog mr-2"></i>系统设置
                    </button>
                <% } %>
            </div>
        </div>

        <!-- 最近活动 -->
        <div class="anime-card p-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-clock mr-2 text-indigo-500"></i>最近活动
            </h3>
            <div id="recentActivity" class="space-y-3">
                <!-- 活动列表将在这里动态加载 -->
                <div class="text-center py-4 text-gray-500">
                    <i class="fas fa-history text-2xl mb-2"></i>
                    <p class="text-sm">暂无活动记录</p>
                </div>
            </div>
        </div>

        <!-- 系统状态 -->
        <div class="anime-card p-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-chart-line mr-2 text-green-500"></i>系统状态
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600">CPU使用率</span>
                    <span class="text-sm font-medium" id="cpuUsage">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-blue-600 h-2 rounded-full" style="width: 0%" id="cpuBar"></div>
                </div>
                
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600">内存使用率</span>
                    <span class="text-sm font-medium" id="memoryUsage">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-green-600 h-2 rounded-full" style="width: 0%" id="memoryBar"></div>
                </div>
                
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600">磁盘使用率</span>
                    <span class="text-sm font-medium" id="diskUsage">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-purple-600 h-2 rounded-full" style="width: 0%" id="diskBar"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建服务器模态框 -->
<div id="createServerModal" class="fixed inset-0 anime-modal hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="anime-modal-content w-full max-w-md">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-bold text-gray-800">创建新服务器</h3>
                    <button onclick="hideCreateServerModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <form id="createServerForm" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">服务器名称</label>
                        <input type="text" name="name" required 
                               class="anime-input w-full" 
                               placeholder="我的Minecraft服务器">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择节点</label>
                        <select name="node_id" required class="anime-input w-full">
                            <option value="">请选择节点</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">服务器类型</label>
                        <select name="server_type" required class="anime-input w-full">
                            <option value="vanilla">原版</option>
                            <option value="spigot">Spigot</option>
                            <option value="paper">Paper</option>
                            <option value="forge">Forge</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">版本</label>
                        <select name="version" required class="anime-input w-full">
                            <option value="latest">最新版本</option>
                            <option value="1.20.1">1.20.1</option>
                            <option value="1.19.4">1.19.4</option>
                            <option value="1.18.2">1.18.2</option>
                            <option value="1.17.1">1.17.1</option>
                        </select>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">端口</label>
                            <input type="number" name="port" required 
                                   class="anime-input w-full" 
                                   placeholder="25565" min="1024" max="65535">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">内存(MB)</label>
                            <input type="number" name="memory" required 
                                   class="anime-input w-full" 
                                   placeholder="1024" min="512" max="8192">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Docker镜像</label>
                        <input type="text" name="docker_image" 
                               class="anime-input w-full" 
                               placeholder="registry.docker-cn.com/itzg/minecraft-server:latest">
                    </div>
                    
                    <div class="flex space-x-3 pt-4">
                        <button type="button" onclick="hideCreateServerModal()" 
                                class="flex-1 bg-gray-300 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-400 transition-all">
                            取消
                        </button>
                        <button type="submit" 
                                class="flex-1 anime-button">
                            创建服务器
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    loadServers();
    loadNodes();
    loadSystemStatus();
    
    // 定时刷新数据
    setInterval(loadDashboardData, 30000); // 30秒刷新一次
    setInterval(loadSystemStatus, 10000); // 10秒刷新系统状态
});

// 加载仪表板数据
async function loadDashboardData() {
    try {
        const response = await fetch('/api/dashboard/stats');
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('myServersCount').textContent = data.stats.my_servers || 0;
            document.getElementById('runningServersCount').textContent = data.stats.running_servers || 0;
            document.getElementById('onlineNodesCount').textContent = data.stats.online_nodes || 0;
        }
    } catch (error) {
        console.error('加载仪表板数据失败:', error);
    }
}

// 加载服务器列表
async function loadServers() {
    try {
        const response = await fetch('/servers');
        const data = await response.json();
        
        if (data.success) {
            const serversList = document.getElementById('serversList');
            
            if (data.servers.length === 0) {
                serversList.innerHTML = `
                    <div class="text-center py-8 text-gray-500">
                        <i class="fas fa-server text-4xl mb-4"></i>
                        <p>暂无服务器，点击上方按钮创建您的第一个服务器</p>
                    </div>
                `;
            } else {
                serversList.innerHTML = data.servers.map(server => `
                    <div class="bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition-all">
                        <div class="flex justify-between items-center">
                            <div class="flex items-center space-x-3">
                                <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-cube text-blue-600"></i>
                                </div>
                                <div>
                                    <h4 class="font-medium text-gray-800">${server.name}</h4>
                                    <p class="text-sm text-gray-600">端口: ${server.port} | 节点: ${server.node_name || '未知'}</p>
                                </div>
                            </div>
                            <div class="flex items-center space-x-2">
                                <span class="anime-badge ${server.status === 'running' ? 'status-running' : 'status-stopped'}">
                                    ${server.status === 'running' ? '运行中' : '已停止'}
                                </span>
                                <div class="flex space-x-1">
                                    ${server.status === 'running' ? 
                                        `<button onclick="stopServer(${server.id})" class="text-red-600 hover:text-red-800 p-1">
                                            <i class="fas fa-stop"></i>
                                        </button>` :
                                        `<button onclick="startServer(${server.id})" class="text-green-600 hover:text-green-800 p-1">
                                            <i class="fas fa-play"></i>
                                        </button>`
                                    }
                                    <button onclick="restartServer(${server.id})" class="text-yellow-600 hover:text-yellow-800 p-1">
                                        <i class="fas fa-redo"></i>
                                    </button>
                                    <button onclick="showServerConsole(${server.id})" class="text-blue-600 hover:text-blue-800 p-1">
                                        <i class="fas fa-terminal"></i>
                                    </button>
                                    <button onclick="deleteServer(${server.id})" class="text-red-600 hover:text-red-800 p-1">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('');
            }
        }
    } catch (error) {
        console.error('加载服务器列表失败:', error);
    }
}

// 加载节点列表
async function loadNodes() {
    try {
        const response = await fetch('/nodes');
        const data = await response.json();
        
        if (data.success) {
            const nodeSelect = document.querySelector('select[name="node_id"]');
            nodeSelect.innerHTML = '<option value="">请选择节点</option>';
            
            data.nodes.forEach(node => {
                const option = document.createElement('option');
                option.value = node.id;
                option.textContent = `${node.name} (${node.host})`;
                nodeSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载节点列表失败:', error);
    }
}

// 加载系统状态
async function loadSystemStatus() {
    try {
        const response = await fetch('/api/system/status');
        const data = await response.json();
        
        if (data.success) {
            const status = data.status;
            
            // 更新CPU使用率
            document.getElementById('cpuUsage').textContent = status.cpu + '%';
            document.getElementById('cpuBar').style.width = status.cpu + '%';
            
            // 更新内存使用率
            document.getElementById('memoryUsage').textContent = status.memory + '%';
            document.getElementById('memoryBar').style.width = status.memory + '%';
            
            // 更新磁盘使用率
            document.getElementById('diskUsage').textContent = status.disk + '%';
            document.getElementById('diskBar').style.width = status.disk + '%';
        }
    } catch (error) {
        console.error('加载系统状态失败:', error);
    }
}

// 显示创建服务器模态框
function showCreateServerModal() {
    document.getElementById('createServerModal').classList.remove('hidden');
}

// 隐藏创建服务器模态框
function hideCreateServerModal() {
    document.getElementById('createServerModal').classList.add('hidden');
}

// 创建服务器表单提交
document.getElementById('createServerForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const data = Object.fromEntries(formData);
    
    try {
        const response = await fetch('/servers/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert('服务器创建成功！', 'success');
            hideCreateServerModal();
            this.reset();
            loadServers();
            loadDashboardData();
        } else {
            showAlert(result.error || '创建服务器失败', 'error');
        }
    } catch (error) {
        showAlert('创建服务器失败：' + error.message, 'error');
    }
});

// 启动服务器
async function startServer(serverId) {
    confirmAction('确定要启动这个服务器吗？', async () => {
        try {
            const response = await fetch(`/servers/${serverId}/start`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (result.success) {
                showAlert('服务器启动成功', 'success');
                loadServers();
                loadDashboardData();
            } else {
                showAlert(result.error || '启动服务器失败', 'error');
            }
        } catch (error) {
            showAlert('启动服务器失败：' + error.message, 'error');
        }
    });
}

// 停止服务器
async function stopServer(serverId) {
    confirmAction('确定要停止这个服务器吗？', async () => {
        try {
            const response = await fetch(`/servers/${serverId}/stop`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (result.success) {
                showAlert('服务器停止成功', 'success');
                loadServers();
                loadDashboardData();
            } else {
                showAlert(result.error || '停止服务器失败', 'error');
            }
        } catch (error) {
            showAlert('停止服务器失败：' + error.message, 'error');
        }
    });
}

// 重启服务器
async function restartServer(serverId) {
    confirmAction('确定要重启这个服务器吗？', async () => {
        try {
            const response = await fetch(`/servers/${serverId}/restart`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (result.success) {
                showAlert('服务器重启成功', 'success');
                loadServers();
                loadDashboardData();
            } else {
                showAlert(result.error || '重启服务器失败', 'error');
            }
        } catch (error) {
            showAlert('重启服务器失败：' + error.message, 'error');
        }
    });
}

// 删除服务器
async function deleteServer(serverId) {
    confirmAction('确定要删除这个服务器吗？此操作不可恢复！', async () => {
        try {
            const response = await fetch(`/servers/${serverId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.success) {
                showAlert('服务器删除成功', 'success');
                loadServers();
                loadDashboardData();
            } else {
                showAlert(result.error || '删除服务器失败', 'error');
            }
        } catch (error) {
            showAlert('删除服务器失败：' + error.message, 'error');
        }
    });
}

// 显示服务器控制台
function showServerConsole(serverId) {
    // 这里可以实现服务器控制台功能
    showAlert('控制台功能开发中...', 'info');
}
</script>

<%- scripts %>